package com.example.rlw.mvpplugintest.mvp;

import com.example.rlw.mvpplugintest.net.ApiException;
import com.example.rlw.mvpplugintest.net.ExceptionUtils;
import com.example.rlw.mvpplugintest.net.HttpResponseData;
import com.orhanobut.logger.Logger;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by rlw on 2018/10/11.
 * 封装的观察者基类
 */

public abstract class BaseObserver<T> implements Observer<HttpResponseData<T>> {

    private BasePresenterImpl mPresenter;
    private BaseView mView;
    private int RESULT_SUCCESS_CODE = 0; //请求成功返回

    public BaseObserver(BaseView view, BasePresenterImpl presenter) {
        this.mView = view;
        this.mPresenter = presenter;
    }

    /**
     * 数据请求成功的回调
     *
     * @param data
     */
    public abstract void onSuccess(T data);

    /**
     * 请求失败的回调
     *
     * @param code
     * @param msg
     */
    public void onFailure(int code, String msg) {
        mView.showFailureView(code, msg);
    }

    @Override
    public void onSubscribe(Disposable d) {
        mPresenter.addSubscription(d);
    }

    @Override
    public void onNext(HttpResponseData<T> tHttpResponseData) {
        //需要根据具体的业务逻辑区分
        if (tHttpResponseData.getState() == RESULT_SUCCESS_CODE) { //请求成功
            mView.showSuccessView(tHttpResponseData.getMsg());
            onSuccess(tHttpResponseData.getData());
        } else { //请求失败
            onFailure(tHttpResponseData.getState(), tHttpResponseData.getMsg());
        }
    }

    @Override
    public void onError(Throwable e) {
        Logger.e("onError" + e);
        ApiException apiException = ExceptionUtils.handleException(e);
        onFailure(apiException.getCode(), apiException.getMsg());
    }

    @Override
    public void onComplete() {
    }
}
